<?php
require_once 'Blog.php';

/**
 *  zend db table
 */
class Application_Model_DbTable_Blogs extends Zend_Db_Table_Abstract
{
    protected $_name = 'ap_blog';
}


/**
 *  
 */
class Blogs extends BaseMapper
{
    protected $_modelName   = 'Blog';
    protected $_dbTableName = 'Application_Model_DbTable_Blogs';

    /* ================================================================================
        access database
    ================================================================================ */

    /**
     *  add Blog
     */
    public function addBlog( $model )
    {
        return $this->_save( $model, 'add' );
    }

    /**
     *  update Blog
     */
    public function updateBlog( $model )
    {
        return $this->_save( $model, 'update' );
    }

    /**
     *  get Blog
     */
    public function getBlog( $id, $status=null )
    {
        // default
        if( null===$status ) {
            $status = Blog::STATUS_OPEN;
        }

        $model = $this->_find($id);
        if( Blog::STATUS_ALL !== $status AND $model->getStatus() !== $status ) {
            return false;
        }
        return $model;
    }

    /**
     *  get many Blogs by user id
     */
    public function getBlogsByUserId( $userId, $status=null )
    {
        // default
        if( null===$status ) {
            $status = Blog::STATUS_OPEN;
        }
        //
        if( Blog::STATUS_ALL == $status ) {
            $status = null;
        }

        $opt = Array(
            'userId' => $userId,
            'status' => $status,
        );
        $models = $this->_getByQuery($opt);
        if( !$models ) {
            return Array();
        }
        
        $allowModels = Array();
        foreach( $models as $model ) {
            if( Blog::STATUS_ALL !== $status AND $model->getStatus() !== $status ) {
                continue;
            }
            $allowModels[] = $model;
        }
        return $allowModels;
    }

    /**
     *  find many Blog
     */
    public function getBlogs( $searchKey=null, $status=null, $page=1, $rowCount=null ) 
    {
        // default
        if( null===$status ) {
            $status = Blog::STATUS_OPEN;
        }
        //
        if( null === $rowCount ) {
            $rowCount = BaseMapper::DEFAULT_ROW_COUNT;
        }

        $opt = Array(
            'status'     => $status,
            '_orderBy'   => ' id DESC ',
            '_searchKey' => $searchKey,
            '_page'      => $page,
            '_rowCount'  => $rowCount,
        );
        return $this->_getByQuery($opt);
    }

    /**
     *  get Blog count
     */
    public function getNumByBlogs( $searchKey=null, $status=null ) 
    {
        // default
        if( null===$status ) {
            $status = Blog::STATUS_OPEN;
        }
        if( Blog::STATUS_ALL == $status ) {
            $status = null;
        }

        $opt = Array(
            'status'     => $status,
            '_searchKey' => $searchKey,
        );
        return $this->_getByQuery($opt,true);
    }

    /**
     *  get Blog query
     */
    protected function _getByQuery( $opt, $isGetTotal=false )
    {
        $this->_checkOption($opt);
        $opt += Array(
            'id'                   => (isset($opt['id'])                   ? (int) ($opt['id'])                   : NULL ),
            'user_id'              => (isset($opt['userId'])               ? (int) ($opt['userId'])               : NULL ),
            'name'                 => (isset($opt['name'])                 ?       ($opt['name'])                 : NULL ),
            'description'          => (isset($opt['description'])          ?       ($opt['description'])          : NULL ),
            'status'               => (isset($opt['status'])               ? (int) ($opt['status'])               : NULL ),
            'createDate'           => (isset($opt['createDate'])           ?       ($opt['createDate'])           : NULL ),
            'updateDate'           => (isset($opt['updateDate'])           ?       ($opt['updateDate'])           : NULL ),
            'properties'           => (isset($opt['properties'])           ?       ($opt['properties'])           : NULL ),
            'normalizedSearch'     => (isset($opt['normalizedSearch'])     ?       ($opt['normalizedSearch'])     : NULL ),

            '_searchKey'           => (isset($opt['_searchKey'])           ?       ($opt['_searchKey'])           : NULL ),
            '_orderBy'             => (isset($opt['_orderBy'])             ?       ($opt['_orderBy'])             : ' id DESC ' ),
            '_page'                => (isset($opt['_page'])                ? (int) ($opt['_page'])                : 1 ),
            '_rowCount'            => (isset($opt['_rowCount'])            ? (int) ($opt['_rowCount'])            : BaseMapper::DEFAULT_ROW_COUNT ),
        );

        if( isset($opt['_page']) && $opt['_page']<=1 ) {
            $opt['_page'] = 1;
        }

        $where = Array();
        if(isset( $opt['id']                  )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' id = ? '                  , $opt['id']                   );  }
        if(isset( $opt['userId']              )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' user_id = ? '             , $opt['userId']               );  }
        if(isset( $opt['name']                )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' name = ? '                , $opt['name']                 );  }
        if(isset( $opt['description']         )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' description = ? '         , $opt['description']          );  }
        if(isset( $opt['status']              )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' status = ? '              , $opt['status']               );  }
        if(isset( $opt['createDate']          )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' create_date = ? '         , $opt['createDate']           );  }
        if(isset( $opt['updateDate']          )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' update_date = ? '         , $opt['updateDate']           );  }
        if(isset( $opt['properties']          )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' properties = ? '          , $opt['properties']           );  }
        if(isset( $opt['normalizedSearch']    )) { $where[] = $this->getDb()->getAdapter()->quoteInto(' normalized_search = ? '   , $opt['normalizedSearch']     );  }

        if( $opt['_searchKey'] ) {
            // 注意: 特殊符號應該要變更一下 => "%" "_" 之類的
            $searchTerms[] = $this->getDb()->getAdapter()->quoteInto(' normalizedSearch LIKE ? ', '%'.$opt['_searchKey'].'%' );
            $where[] = ' ( '. join(' OR ',$searchTerms) . ' ) ';
        }

        // where from array to string
        $whereString = join(' AND ',$where);
        if(!$whereString) {
            $whereString = null;
        }

        // get total
        if( $isGetTotal ) {
            $select = $this->getDb()->select();
            $select->from( $this->getDb(), Array('COUNT(*) AS total') );
            if($whereString) {
                $select->where( $whereString );
            }
            $rows = $this->getDb()->fetchRow($select);
            $row = $rows->toArray();
            return (int) $row['total'];
        }

        //
        //echo $whereString; exit;

        //
        if( NULL === $opt['_page'] ) {
            $rowset = $this->getDb()->fetchAll($whereString, $opt['_orderBy']);
        }
        else {
            $offset = ($opt['_page']-1) * $opt['_rowCount'];
            $rowset = $this->getDb()->fetchAll($whereString, $opt['_orderBy'], $opt['_rowCount'], $offset );
        }
        if( !$rowset ) {
            return NULL;
        }

        $models = Array();
        foreach( $rowset as $row ) {
            $models[] = $this->mapRow( $row->toArray() );
        }
        return $models;

    }

    /* ================================================================================
        about model object
    ================================================================================ */

    /**
     *  set mapRow by pure database record
     */
    public function mapRow($row)
    {
        //properties
        is_array($row["properties"])
            ? $row["properties"] = unserialize($row["properties"])
            : $row["properties"] = Array();

        $model = $this->getModel();
        $model->setId               ( $row['id']                     );
        $model->setUserId           ( $row['user_id']                );
        $model->setName             ( $row['name']                   );
        $model->setDescription      ( $row['description']            );
        $model->setStatus           ( $row['status']                 );
        $model->setCreateDate       ( strtotime($row['create_date']) );
        $model->setUpdateDate       ( strtotime($row['update_date']) );
        $model->setProperties       ( $row['properties']             );
        $model->setNormalizedSearch ( $row['normalized_search']      );
        return $model;
    }

}

